﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;

public partial class Admin_Components_MasterData_Shop : System.Web.UI.UserControl
{
    DBDataContext db;
    DatabaseHelper helper;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            ResetForm(); 
        }
    }
    private void ResetForm()
    {
        try
        {
            txtShopCode.Text = GernerateCode();
            gvLocation.DataSource = new DataTable();
            gvLocation.DataBind();
            Utils.loadLocation(cbProvince, 0, 0);
            Utils.loadLocation(cbProvinceMain, 0, 0);
            gvData.DataSource = new DataTable();
            gvData.DataBind();
            rtpFromDateSearch.SelectedDate = DateTime.Now.Date;
            rtpToDateSearch.SelectedDate = DateTime.Now.Date;
        }
        catch (Exception ex)
        {
            ControlUtil.LogError("Shop Page-loadForm:" + ex.Message);
        }
    }
    private DataTable createTable()
    {
        DataTable dt = null;
        try
        {
            if (ViewState["TBLListLocation"] == null)
            {
                dt = new DataTable();
                dt.Columns.Add("LocationID", System.Type.GetType("System.String"));
                dt.Columns.Add("ProvinceName", System.Type.GetType("System.String"));
                dt.Columns.Add("DistrictName", System.Type.GetType("System.String"));
            }
            else dt = (DataTable)ViewState["TBLListLocation"];
        }
        catch (Exception ex)
        {
            ControlUtil.LogError("Shop Page-createTable:" + ex.Message.ToString());
        }
        return dt;
    }
    private void addDataToTable()
    {
        try
        {
            string LocationID = cbProvince.SelectedValue.ToString() + "|" + cbDistrict.SelectedValue.ToString();
            DataTable dt = createTable();
            //check ma san pham da chon chua, neu đa ton tai thi update
            DataRow[] rowArr = dt.Select("LocationID='" + LocationID + "'");
            if (rowArr.Count() > 0)
            {
                DataRow row = rowArr[0];
                row.Delete();
                dt.AcceptChanges();
            }
            DataRow drNew = dt.NewRow();

            drNew["LocationID"] = LocationID;
            drNew["ProvinceName"] = cbProvince.SelectedItem.Text.Trim();
            drNew["DistrictName"] = cbDistrict.SelectedItem.Text.Trim();
            dt.Rows.Add(drNew);
            ViewState["TBLListLocation"] = dt;
            gvLocation.DataSource = dt;
            gvLocation.DataBind();
        }
        catch (Exception ex)
        {
            ControlUtil.LogError("Shop Page-addDataToTable:" + ex.Message.ToString());
        }
    }
    private string GernerateCode()
    {
        string strCode = string.Empty;
        try
        {
            //Fortmat: LC00000001
            /*
         
              int lenZero = 7;//So ky tu khôg tính chữ cái đưungs đầu. ví dụ KH0000001 --> 7, k tính KH
                var customerCodeMax = dbread.Customers.Max(d => d.OrderNumber);
                int MaxOrderNumber = (customerCodeMax == null ? 0 : Convert.ToInt32(customerCodeMax)) + 1;
                String LastCode = ("000000" + MaxOrderNumber).ToString();
                String CustomerCode = "KH" + LastCode.Substring(LastCode.Length - lenZero);
             */

            db = new DBDataContext();
            var PurchaseOrderMax = db.Shops.Max(d => d.OrderNumber);
            int MaxOrderNumber = (PurchaseOrderMax == null ? 0 : Convert.ToInt32(PurchaseOrderMax)) + 1;
            String strLastCode = "000" + MaxOrderNumber.ToString();
            strCode = "CH" + strLastCode.Substring(strLastCode.Length - 3);
        }
        catch (Exception ex)
        {
            ControlUtil.LogError("Shop Page-GernerateCode:" + ex.Message);
            //ResetForm();
        }
        return strCode;
    }
    private List<ShopLocation> insertShopLocation(int iShopID = 0)
    {
        try
        {
            List<ShopLocation> listDetail = new List<ShopLocation>();
            foreach (GridDataItem item in gvLocation.Items)
            {
                string[] arr = Utils.KillChars(item["LocationID"].Text.Trim()).Split('|');
                ShopLocation soDetail = new ShopLocation();
                soDetail.ShopID = iShopID;
                soDetail.ProvinceID = Convert.ToInt32(arr[0]);
                soDetail.DistrictID = Convert.ToInt32(arr[1]);
                soDetail.CreatedBy = Session["UserName"].ToString();
                soDetail.LastUpdatedBy = Session["UserName"].ToString();
                soDetail.CreatedDateTime = DateTime.Now;
                soDetail.LastUpdatedDateTime = DateTime.Now;
                soDetail.Status = 'A';
                listDetail.Add(soDetail);
            }
            return listDetail;
        }
        catch (Exception ex)
        {
            ControlUtil.LogError("Shop Page-insertShopLocation:" + ex.Message);
            return null;
        }
    }
    private void deleteDetail(int iID = 0)
    {
        try
        {
            if (iID != 0)
            {
                List<ShopLocation> soDetail = (from sd in db.ShopLocations where sd.ShopID == iID select sd).ToList<ShopLocation>();
                db.Delete<ShopLocation>(soDetail);
                db.SubmitChanges();
            }
        }
        catch (Exception ex)
        {
            ControlUtil.LogError("Shop Page-deleteDetail:" + ex.Message.ToString());
        }
    }
    private void getDataSearch()
    {
        ProShop pro = new ProShop();
        pro.strShopCodeSearch = Utils.KillChars(txtShopCodeSearch.Text.Trim());
        pro.strShopNameSearch = Utils.KillChars(txtShopNameSearch.Text.Trim());
        pro.strTypeSearch = Utils.KillChars(cbTypeSearch.SelectedValue.Trim().ToString());
        pro.strStartDate = Utils.KillChars(this.rtpFromDateSearch.SelectedDate == null ? "" : String.Format("{0:dd/MM/yyyy}", this.rtpFromDateSearch.SelectedDate));
        pro.strEndDate = Utils.KillChars(this.rtpToDateSearch.SelectedDate == null ? "" : String.Format("{0:dd/MM/yyyy}", this.rtpToDateSearch.SelectedDate));

        loadData(pro);
    }
    private void loadData(ProShop pro)
    {
        try
        {
            int PageNumber = gvData.CurrentPageIndex + 1;
            int PageSize = gvData.PageSize;

            helper = new DatabaseHelper();
            System.Data.Common.DbParameter paramID = helper.Parameter;
            paramID.ParameterName = "ShopID";
            paramID.DbType = DbType.Int32;
            paramID.Value = -1;
            helper.AddParameter(paramID);

            System.Data.Common.DbParameter paramCode = helper.Parameter;
            paramCode.ParameterName = "ShopCode";
            paramCode.DbType = DbType.String;
            paramCode.Value = pro.strShopCodeSearch;
            helper.AddParameter(paramCode);

            System.Data.Common.DbParameter paramName = helper.Parameter;
            paramName.ParameterName = "ShopName";
            paramName.DbType = DbType.String;
            paramName.Value = pro.strShopNameSearch;
            helper.AddParameter(paramName);

            System.Data.Common.DbParameter paramType = helper.Parameter;
            paramType.ParameterName = "Type";
            paramType.DbType = DbType.String;
            paramType.Value = pro.strTypeSearch;
            helper.AddParameter(paramType);

            System.Data.Common.DbParameter paramStartDate = helper.Parameter;
            paramStartDate.ParameterName = "StartDate";
            paramStartDate.DbType = DbType.String;
            paramStartDate.Value = pro.strStartDate;
            helper.AddParameter(paramStartDate);

            System.Data.Common.DbParameter paramEndDate = helper.Parameter;
            paramEndDate.ParameterName = "EndDate";
            paramEndDate.DbType = DbType.String;
            paramEndDate.Value = pro.strEndDate;
            helper.AddParameter(paramEndDate);

            System.Data.Common.DbParameter paramPageNumber = helper.Parameter;
            paramPageNumber.ParameterName = "PageNumber";
            paramPageNumber.DbType = DbType.Int32;
            paramPageNumber.Value = PageNumber;
            helper.AddParameter(paramPageNumber);

            System.Data.Common.DbParameter paramPageSize = helper.Parameter;
            paramPageSize.ParameterName = "PageSize";
            paramPageSize.DbType = DbType.Int32;
            paramPageSize.Value = PageSize;
            helper.AddParameter(paramPageSize);
            DataTable dt = helper.ExecuteDataTable("Admin_GetShop", CommandType.StoredProcedure, ConnectionState.CloseOnExit);
            if (dt.Rows.Count > 0)
            {
                gvData.Height = 250;
                gvData.ClientSettings.Scrolling.AllowScroll = true;
                gvData.ClientSettings.Scrolling.UseStaticHeaders = true;
                gvData.VirtualItemCount = Convert.ToInt32(dt.Rows[0]["TotalRows"]);
                div_TotalRows.InnerText = "Kết quả tìm kiếm: " + dt.Rows[0]["TotalRows"].ToString();
                gvData.DataSource = dt;
            }
            else
            {
                gvData.DataSource = new DataTable();
                div_TotalRows.InnerText = "Kết quả tìm kiếm: 0";
            }

            //gvData.DataBind();
        }
        catch (Exception ex)
        {
            ControlUtil.LogError("PurchaseOrder Page-loadData:" + ex.Message);
        }
    }
    private DataTable DTShopLocation(int ID = 0)
    {
        //DataTable dt = null;
        try
        {
            db = new DBDataContext();
            var list = (from a in db.ShopLocations
                        join b in db.Locations on a.ProvinceID equals b.ID
                        join c in db.Locations on a.DistrictID equals c.ID
                        where a.ShopID == ID && a.Status == 'A' 
                        select new
                        {
                            LocationID = b.ID + "|" + c.ID,
                            ProvinceName = b.LocationName,
                            DistrictName = c.LocationName,
                            
                        }).ToList();


            return list.ToDataTable();
        }
        catch (Exception ex)
        {
            ControlUtil.LogError("Shop Page-DTShopLocation:" + ex.Message.ToString());
            return new DataTable();
        }

    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        if (Session["Username"] != null)
        {
            try
            {
                if (string.IsNullOrEmpty(cbType.SelectedValue.Trim()))
                {
                    JavascriptUtil.LoadMessage(UpdatePanel1, false, "Vui lòng chọn loại Cửa hàng!");
                    txtAddress.Focus();
                    return;
                }
                if (string.IsNullOrEmpty(txtShopName.Text.Trim()))
                {
                    JavascriptUtil.LoadMessage(UpdatePanel1, false, "Vui lòng nhập tên Cửa hàng!");
                    txtShopName.Focus();
                    return;
                }
                if (string.IsNullOrEmpty(cbProvinceMain.SelectedValue.Trim()))
                {
                    JavascriptUtil.LoadMessage(UpdatePanel1, false, "Vui lòng nhập tỉnh/thành phố Cửa hàng!");
                    cbProvinceMain.Focus();
                    return;
                }
                if (string.IsNullOrEmpty(txtAddress.Text.Trim()))
                {
                    JavascriptUtil.LoadMessage(UpdatePanel1, false, "Vui lòng nhập địa chỉ Cửa hàng!");
                    txtAddress.Focus();
                    return;
                }
                if (cbType.SelectedValue.Trim() != "W")
                {
                    if (gvLocation.Items.Count == 0)
                    {
                        JavascriptUtil.LoadMessage(UpdatePanel1, false, "Vui lòng thêm danh sách tỉnh/thành phố theo Cửa hàng!");
                        gvLocation.Focus();
                        return;
                    }
                }
                db = new DBDataContext();
                if (ViewState["ShopID"] == null)
                {
                    string strCode = GernerateCode();
                    Shop obj = new Shop();
                    obj.ShopCode = strCode;
                    obj.OrderNumber = Convert.ToInt32(Utils.KillChars(strCode.Substring(2, strCode.Length - 2)));
                    obj.ShopName = Utils.KillChars(txtShopName.Text.Trim());
                    obj.ProvinceID = Convert.ToInt32(Utils.KillChars(cbProvinceMain.SelectedValue.Trim()));
                    obj.Address = Utils.KillChars(txtAddress.Text.Trim());
                    obj.PhoneNumber = Utils.KillChars(txtPhoneNumber.Text.Trim());
                    obj.ShopType = Utils.KillChars(cbType.SelectedValue);
                    obj.CreatedBy = Session["Username"].ToString();
                    obj.CreatedDateTime = DateTime.Now;
                    obj.LastUpdatedBy = Session["Username"].ToString();
                    obj.LastUpdatedDateTime = DateTime.Now;
                    obj.Status = 'A';
                    db.Insert<Shop>(obj);
                    db.SubmitChanges();
                    ViewState["ShopID"] = obj.ID;
                }
                else
                {
                    Shop obj = db.Shops.FirstOrDefault(x => x.ID == Convert.ToInt32(ViewState["ShopID"]));
                    obj.ShopName = Utils.KillChars(txtShopName.Text.Trim());
                    obj.Address = Utils.KillChars(txtAddress.Text.Trim());
                    obj.ProvinceID = Convert.ToInt32(Utils.KillChars(cbProvinceMain.SelectedValue.Trim()));
                    obj.PhoneNumber = Utils.KillChars(txtPhoneNumber.Text.Trim());
                    obj.ShopType = Utils.KillChars(cbType.SelectedValue);
                    obj.LastUpdatedBy = Session["Username"].ToString();
                    obj.LastUpdatedDateTime = DateTime.Now;
                    db.SubmitChanges();
                }
                
                
                
                //delete du lieu cu
                deleteDetail(Convert.ToInt32(ViewState["ShopID"]));
                if (cbType.SelectedValue != "W")
                {
                    db.Insert<ShopLocation>(insertShopLocation(Convert.ToInt32(ViewState["ShopID"])));
                }
                db.SubmitChanges();
                JavascriptUtil.LoadMessage(UpdatePanel1, true, "Lưu thành công!");
                btnSave.Enabled = false;
            }
            catch (Exception ex)
            {
                JavascriptUtil.LoadMessage(UpdatePanel1, false, "Thông báo lỗi: Lưu không thành công, vui lòng kiểm tra dữ liệu!");
                ControlUtil.LogError("Shop Page-Save:" + ex.Message);
            }
        }
    }
    protected void btnCancel_Click(object sender, EventArgs e)
    {
        if (Session["Username"] != null)
        {
            try
            {
                if (ViewState["ShopID"] != null)
                {
                    db = new DBDataContext();
                    Shop obj = db.Shops.FirstOrDefault(x => x.ID == Convert.ToInt32(ViewState["ShopID"]));
                    obj.LastUpdatedBy = Session["Username"].ToString();
                    obj.LastUpdatedDateTime = DateTime.Now;
                    obj.Status = 'I';

                    var list = (from a in db.ShopLocations
                                where a.ShopID == Convert.ToInt32(ViewState["ShopID"]) && a.Status == 'A'
                                select a
                        ).ToList();
                    
                    foreach(var p in list)
                    {
                        p.Status = 'I';
                        p.LastUpdatedDateTime = DateTime.Now;
                        p.LastUpdatedBy = Session["Username"].ToString();
                    }
                    db.SubmitChanges();
                    btnCancel.Enabled = false;
                    btnSave.Enabled = false;
                    JavascriptUtil.LoadMessage(UpdatePanel1, true, "Xóa thành công!");

                }
            }
            catch (Exception ex)
            {
                ControlUtil.LogError("Shop Page-btnCancel_Click:" + ex.Message.ToString());
                JavascriptUtil.LoadMessage(UpdatePanel1, false, "Thông báo lỗi: Xóa không thành công. Vui lòng kiểm tra dữ liệu và thực hiện lại!");
            }
        }
    }
    protected void btnNew_Click(object sender, EventArgs e)
    {
        Response.Redirect("/Shop", false);
    }
    protected void gvLocation_ItemCommand(object sender, Telerik.Web.UI.GridCommandEventArgs e)
    {
        try
        {
            string commandName = e.CommandName;
            string strProductID = e.CommandArgument.ToString();//Lay ID 
            
            if (commandName == "DeleteItem")
            //if (commandName == "DeleteItem")
            {
                try
                {
                    DataTable dt = (DataTable)ViewState["TBLListLocation"];
                    DataRow[] rowArr = dt.Select("LocationID='" + strProductID + "'");
                    if (rowArr.Count() > 0)
                    {
                        DataRow row = rowArr[0];
                        row.Delete();
                        dt.AcceptChanges();

                    }
                    ViewState["TBLListLocation"] = dt;
                    div_TotalProduct.InnerText = "Tổng cộng: " + gvLocation.Items.Count.ToString();
                    gvLocation.DataSource = dt;
                    gvLocation.DataBind();
                }
                catch (Exception ex)
                {
                    ControlUtil.LogError("Shop Page-gvLocation_ItemCommand-DeleteItem:" + ex.Message);
                    JavascriptUtil.LoadMessage(UpdatePanel1, false, "Thông báo lỗi: Xóa không thành công!");
                }
            }
        }
        catch (Exception ex)
        {
            ControlUtil.LogError("Shop Page-gvLocation_ItemCommand:" + ex.Message);
        }
    }
    protected void btnAdd_Click(object sender, EventArgs e)
    {
        if (string.IsNullOrEmpty(cbProvince.SelectedValue.ToString()))
        {
            JavascriptUtil.LoadMessage(UpdatePanel1, false, "Vui lòng chọn Tỉnh/thành phố!");
            cbProvince.Focus();
            return;
        }
        if (string.IsNullOrEmpty(cbDistrict.SelectedValue.ToString()))
        {
            JavascriptUtil.LoadMessage(UpdatePanel1, false, "Vui lòng chọn Huyện/quận!");
            cbDistrict.Focus();
            return;
        }
        addDataToTable();
    }
    protected void btnSearch_Click(object sender, EventArgs e)
    {
        getDataSearch();
        gvData.DataBind();
    }
    protected void cbProvince_SelectedIndexChanged(object o, RadComboBoxSelectedIndexChangedEventArgs e)
    {
        Utils.loadLocation(cbDistrict, Convert.ToInt32(cbProvince.SelectedValue), 0);
    }
    protected void cbType_SelectedIndexChanged(object o, RadComboBoxSelectedIndexChangedEventArgs e)
    {
        btnAdd.Enabled = true;
        if (cbType.SelectedValue == "W")
        {
            btnAdd.Enabled = false;
            gvLocation.DataSource = new DataTable();
            gvLocation.DataBind();
        }
        
    }
    protected void btnRefresh_Click(object sender, EventArgs e)
    {
        getDataSearch();
        gvData.DataBind();
    }
    protected void gvData_ItemCommand(object sender, Telerik.Web.UI.GridCommandEventArgs e)
    {
        if (Session["Username"] != null)
        {
            try
            {
                string commandName = e.CommandName;
                int ID = Convert.ToInt32(e.CommandArgument.ToString());//Lay ID 
                helper = new DatabaseHelper();
                

                if (commandName == "EditItem")
                {
                    try
                    {
                        RadPageView1.Selected = true;
                        TabStrip1.SelectedIndex = 0;
                        System.Data.Common.DbParameter paramNewsID = helper.Parameter;
                        paramNewsID.ParameterName = "ShopID";
                        paramNewsID.DbType = DbType.Int32;
                        paramNewsID.Value = ID;
                        helper.AddParameter(paramNewsID);
                        DataTable dt = helper.ExecuteDataTable("Admin_GetShop", CommandType.StoredProcedure, ConnectionState.CloseOnExit);
                        if (dt.Rows.Count > 0)
                        {
                            txtShopCode.Text = dt.Rows[0]["ShopCode"].ToString();
                            txtShopName.Text = dt.Rows[0]["ShopName"].ToString();
                            cbType.SelectedValue = dt.Rows[0]["ShopType"].ToString();
                            cbProvinceMain.SelectedValue = dt.Rows[0]["ProvinceID"].ToString();
                            txtAddress.Text = dt.Rows[0]["Address"].ToString();
                            txtPhoneNumber.Text = dt.Rows[0]["PhoneNumber"].ToString();
                            txtLastUpdatedBy.Text = dt.Rows[0]["LastUpdatedBy"].ToString();
                            txtLastUpdatedDateTime.Text = dt.Rows[0]["LastUpdatedDateTime"].ToString();
                            ViewState["ShopID"] = ID;
                            //ViewState["TBLListLocation"] = ID;
                           
                            DataTable dtShopLocation = DTShopLocation(Convert.ToInt32(ID));
                            if (dtShopLocation.Rows.Count > 0)
                            {
                                ViewState["TBLListLocation"] = dtShopLocation;
                                
                            }
                            else
                            {
                                ViewState["TBLListLocation"] = null;

                            }
                            gvLocation.DataSource = dtShopLocation;
                            gvLocation.DataBind();
                            div_TotalProduct.InnerText = "Tổng cộng: " + gvLocation.Items.Count.ToString();
                            if (cbType.SelectedValue == "W")
                                btnAdd.Enabled = false;
                            btnCancel.Enabled = true;
                            btnSave.Enabled = true;
                        }
                    }
                    catch (Exception ex)
                    {
                        ControlUtil.LogError("StockTransfer Page-gvData_ItemCommand-EditItem:" + ex.Message);
                    }
                }
                //else if (commandName == "DeleteItem")
                //{
                //    try
                //    {
                //        delete(ID);
                //        JavascriptUtil.LoadMessage(UpdatePanel1, true, "Xóa tin thành công!");
                //        gvData.Rebind();
                //    }
                //    catch (Exception ex)
                //    {
                //        ControlUtil.LogError("StockTransfer Page-gvData_ItemCommand-DeleteItem:" + ex.Message);
                //        JavascriptUtil.LoadMessage(UpdatePanel1, false, "Thông báo lỗi: Xóa không thành công!");
                //    }
                //}
            }
            catch (Exception ex)
            {
                ControlUtil.LogError("StockTransfer Page-gvData_ItemCommand:" + ex.Message);
            }
        }
    }
    protected void gvData_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
    {
        try
        {
            //Ham phan trang: Paging
            if (RadPageView3.Selected)
            {
                TabStrip1.SelectedIndex = 3;
                gvData.Height = 250;
                gvData.Visible = true;
                getDataSearch();
            }
            else
            {
                gvData.DataSource = new DataTable();
            }
        }
        catch (Exception ex)
        {
            ControlUtil.LogError("Shop Page-gvData_NeedDataSource:" + ex.Message);
        }
    }

    #region Properties
    public class ProShop
    {
        public string strTransferOrderCode { get; set; }
        public string strRemark { get; set; }
        public string strType { get; set; }
        public string LastUpdatedBy { get; set; }
        public string LastUpdatedDateTime { get; set; }
        public string strShopNameSearch { get; set; }
        public string strStartDate { get; set; }
        public string strEndDate { get; set; }
        public string strTypeSearch { get; set; }
        public string strShopCodeSearch { get; set; }
    }
    #endregion End Properties
}